package com.itfenghuang.Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse) response;
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //将一些请求放行,获取映射路径
        String servletPath = req.getServletPath();
        if ("/loginServlet".equals(servletPath)
            || "/registerServlet".equals(servletPath)
            ||"/register.jsp".equals(servletPath)
            ||"/validateServlet".equals(servletPath)){
            chain.doFilter(req,resp);
            return;
        }
        /**
         * 代码逻辑
         * 针对某些请求过滤,未登录前所有的请求都要过滤
         * 针对某些请求放行  访问登陆页面,登陆的servlet,注册功能
         * 如何判断是否已经登陆?  登陆servlet中添加到会话域中
         */
        HttpSession session = req.getSession();
        Object username = session.getAttribute("username");
        //判断username是否为空
        if (username!=null){
            chain.doFilter(req,resp);
        }else {
            //转发到登陆界面
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
